<template>
  <div class="gap-col-8">
    <div class="d-flex justify-center text-gray-x2 font-size-12 -mt-8">{{ $t('info.feedbackProblem') }}</div>
    <Selector
      v-model="reason"
      :items="reasons"
      item-title="content"
      item-value="id"
      :label="$t('info.questionType')"
      :placeholder="$t('info.selectType')"
    ></Selector>
    <div v-if="reasonErr" class="font-size-12 font-weight-400 line-height-120 text-primary-x text-right">
      {{ reasonErr }}
    </div>
    <TextareaWrap
      v-model="content"
      :err-msg="contentErr"
      bg-dark
      :label="$t('info.detailedReason')"
      :placeholder="$t('placeholder.detailedReason')"
      :line="5"
    ></TextareaWrap>
    <div class="position-relative">
      <div ref="fileList" class="d-flex w-full overflow-auto gap-row-8 position-relative">
        <div v-for="(file, index) in files" :key="index" class="file">
          <div class="name font-size-12 line-height-140">{{ file.name }}</div>
          <div class="font-size-8 line-height-140">{{ file.sizeKB }}KB {{ file.type.toUpperCase() }}</div>
          <div class="delete" @click="removeFile(index)"><Icon name="close" size="10"></Icon></div>
        </div>
      </div>
      <div v-if="isDesktop && files.length >= 3">
        <div v-if="canScrollLeft || !canScrollRight" class="arrow arrow-left" @click="scrollLeft">
          <Icon name="arrowRight" size="16" style="transform: scaleX(-1)"></Icon>
        </div>
        <div v-else-if="canScrollRight || !canScrollLeft" class="arrow arrow-right" @click="scrollRight">
          <Icon name="arrowRight" size="16"></Icon>
        </div>
      </div>
    </div>
    <input
      ref="inputImage"
      type="file"
      accept="image/jpg, image/jpeg, image/png, image/gif"
      @change="(event) => handleFileUpload(event)"
      hidden
      multiple
    />
    <div
      class="list d-flex justify-center align-center pointer bg-background py-2 rounded-pill font-size-11"
      @click="() => inputImage.click()"
    >
      <Icon name="add"></Icon>
      <div class="font-size-14 font-weight-500">{{ $t('content.addImage') }}</div>
    </div>
    <InputWrap
      bgDark
      v-model="email.value"
      :err-msg="email.error"
      :label="$t('label.email')"
      :placeholder="$t('placeholder.email')"
    ></InputWrap>
  </div>
</template>

<script setup>
import { nextTick, reactive, ref } from 'vue'
import { storeToRefs } from 'pinia'
import { useAppStore } from '@/store/app'
import { useDialogStore } from '@/store/dialog'
import { useFeedback } from '@/store/feedback.js'
import { usePopupMessageStore } from '@/store/popup-message'
import { $t } from '@/i18n'
import { useYup, validateSync } from '@/plugins/yup'
import InputWrap from '@/components/form/InputWrap.vue'
import Selector from '@/components/form/Selector.vue'
import TextareaWrap from '@/components/form/TextareaWrap.vue'
import { useConfirmData } from '@/compositions/dialog/confirm-data'
import uploadImage from '@/http/upload/uploadImage'

const { open: openMessage } = usePopupMessageStore()
const feedback = useFeedback()
const { reasons, reason, reasonErr, content, contentErr, filesUrl, files } = storeToRefs(feedback)
const Yup = useYup()
const inputImage = ref(null)
const { isDesktop } = storeToRefs(useAppStore())
const dialogStore = useDialogStore()
const { loadingMask } = storeToRefs(dialogStore)

const email = reactive({
  value: '',
  error: '',
  check: false,
})
const schemaEmail = Yup.string().required().email()

// 圖片(上傳與刪除)
const handleFileUpload = async (event) => {
  const uploadedFiles = event.target.files
  const newFiles = []

  if (files.value.length + uploadedFiles.length > 6) {
    openMessage($t('content.mostUploadImg', { count: 6 }))
    return
  }

  for (let i = 0; i < uploadedFiles.length; i++) {
    const file = uploadedFiles[i]

    try {
      loadingMask.value = true
      const url = await uploadImage(file, () => {})
      newFiles.push({
        name: file.name,
        sizeKB: (file.size / 1024).toFixed(2), // 將大小轉換為 KB 並保留兩位小數
        type: file.type.split('/')[1], // 獲取檔案類型（如 jpg, png）
        url: url,
      })
    } catch (error) {
      console.error(error)
    } finally {
      loadingMask.value = false
    }
  }

  files.value.push(...newFiles)

  nextTick(() => {
    updateScrollButtons()
  })
}
const removeFile = (index) => {
  files.value.splice(index, 1)
  nextTick(() => {
    updateScrollButtons()
  })
}

// 圖片檔案的左右滑動功能
const fileList = ref(null)
const canScrollLeft = ref(false)
const canScrollRight = ref(false)

const updateScrollButtons = () => {
  const el = fileList.value
  canScrollLeft.value = el.scrollLeft > 0
  canScrollRight.value = el.scrollWidth > el.clientWidth && el.scrollLeft < el.scrollWidth - el.clientWidth
}

const scrollRight = () => {
  const el = fileList.value
  const maxScrollLeft = el.scrollWidth - el.clientWidth

  const handleScroll = () => {
    if (el.scrollLeft >= maxScrollLeft) {
      el.removeEventListener('scroll', handleScroll)
    }
    updateScrollButtons()
  }

  el.addEventListener('scroll', handleScroll)
  el.scrollTo({ left: maxScrollLeft, behavior: 'smooth' })
}

const scrollLeft = () => {
  const el = fileList.value

  const handleScroll = () => {
    if (el.scrollLeft === 0) {
      el.removeEventListener('scroll', handleScroll)
    }
    updateScrollButtons()
  }

  el.addEventListener('scroll', handleScroll)
  el.scrollTo({ left: 0, behavior: 'smooth' })
}

// 表單驗證後數據送出
useConfirmData(validator)
function validator() {
  let isValid = true

  if (reason.value === null) {
    reasonErr.value = $t('yup.mixed.required')
    isValid = false
  } else {
    reasonErr.value = ''
  }

  if (content.value === '') {
    contentErr.value = $t('yup.mixed.required')
    isValid = false
  } else {
    contentErr.value = ''
  }

  validateSync(schemaEmail, email)
  if (!email.check) {
    isValid = false
  }

  if (!isValid) {
    return false
  }

  filesUrl.value = files.value.map((file) => file.url)

  const data = { type: reason.value, content: content.value, attachment: filesUrl.value, email: email.value }
  return data
}
</script>
<style lang="scss" scoped>
.file {
  border-radius: 0.625rem;
  padding: 0.5rem;
  color: #b8b8b8;
  background: #181925;
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  position: relative;

  & .name {
    max-width: 4.875rem;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    display: inline-block;
    margin-bottom: 0.25rem;
    padding-right: 0.625rem;
  }
  & .delete {
    padding-right: 0.375rem;
    position: absolute;
    cursor: pointer;
    right: 0;
    top: 0;
  }
}
.arrow {
  position: absolute;
  top: 50%;
  transform: translate(0, -50%);
  background: #b8b8b805;
  backdrop-filter: blur(0.625rem);
  width: 2rem;
  height: 2rem;
  padding-left: 0.5rem;
  border-radius: 1.875rem 0rem 0rem 1.875rem;

  cursor: pointer;
  display: flex;
  align-items: center;

  &-right {
    right: 0;
    border-radius: 30px 0px 0px 30px;
  }
  &-left {
    left: 0;
    border-radius: 0px 30px 30px 0px;
  }
}
.-mt-8 {
  margin-top: -0.5rem;
}
</style>
